<template>
  <div class="user-profile-header">
    <div class="profile-main">
      <div class="avatar-section">
        <div class="avatar-wrapper">
          <a-avatar 
            :src="getMinioFileUrl(userInfo?.filePath) || 'https://via.placeholder.com/80x80'" 
            :size="80"
            class="user-avatar"
          />
          <div class="avatar-upload-overlay" @click="triggerFileUpload">
            <CameraOutlined class="upload-icon" />
          </div>
        </div>
        <input
          ref="fileInput"
          type="file"
          accept="image/*"
          style="display: none"
          @change="handleFileChange"
        />
      </div>
      
      <div class="user-info">
        <div class="username-section">
          <h2 class="username">{{ userInfo?.username}}</h2>
          <EditOutlined class="edit-icon" @click="showEditModal = true" />
        </div>
        <div class="account-info">
          <div class="email-info" v-if="userInfo?.email">
            <MailOutlined class="icon" />
            <span>邮箱: {{ userInfo.email }}</span>
          </div>
          <div class="gender-info">
            <WomanOutlined v-if="userInfo?.sex === 1" class="gender-icon female" />
            <ManOutlined v-else class="gender-icon male" />
            <span>{{ userInfo?.sex === 1 ? '女' : '男' }}</span>
          </div>
        </div>
      </div>
    </div>
    
    <div class="divider"></div>
    
    <UserProfileEditModal
      v-model:open="showEditModal"
      :user-info="userInfo"
      @profile-updated="handleProfileUpdated"
    />
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import { 
  EditOutlined, 
  CameraOutlined, 
  WomanOutlined, 
  ManOutlined,
  MailOutlined
} from '@ant-design/icons-vue'
import { updateUser } from '@/api/user/sysUserController'
import { uploadPic } from '@/api/media/bizFilesController'
import UserProfileEditModal from './UserProfileEditModal.vue'
import { useAuthStore } from '@/stores/authStore'

// 获取MinIO文件完整URL的工具函数
const getMinioFileUrl = (filePath?: string): string => {
  if (!filePath) {
    return 'https://via.placeholder.com/80x80'
  }
  
  // 如果已经是完整URL，直接返回
  if (filePath.startsWith('http://') || filePath.startsWith('https://')) {
    return filePath
  }
  
  // 否则拼接MinIO基础URL
  const minioUrl = import.meta.env.VITE_MINIO_URL || 'http://172.172.2.99:9000'
  return `${minioUrl}${filePath}`
}

interface UserInfo {
  userId?: number
  username?: string
  nickname?: string
  email?: string
  sex?: number
  phone?: string
  filePath?: string
  douyinId?: string
}

interface Stats {
  following?: number
  followers?: number
  likes?: number
  liveCount?: number
}

interface Props {
  userInfo?: UserInfo
  stats?: Stats
}

const props = withDefaults(defineProps<Props>(), {
  userInfo: () => ({}),
  stats: () => ({})
})

const emit = defineEmits<{
  'profile-updated': [userInfo: UserInfo]
}>()

const fileInput = ref<HTMLInputElement>()
const showEditModal = ref(false)
const authStore = useAuthStore()

const triggerFileUpload = () => {
  fileInput.value?.click()
}

const handleFileChange = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  
  if (!file) return
  
  // 文件大小检查 (2MB)
  if (file.size > 2 * 1024 * 1024) {
    message.error('文件大小不能超过2MB')
    return
  }
  
  // 文件类型检查
  if (!file.type.startsWith('image/')) {
    message.error('请选择图片文件')
    return
  }
  
  // 检查文件格式
  const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp']
  if (!allowedTypes.includes(file.type)) {
    message.error('只支持 JPG、PNG、GIF、WebP 格式的图片')
    return
  }
  
  // 检查文件是否为空
  if (file.size === 0) {
    message.error('文件不能为空')
    return
  }
  
  try {
    // 直接使用成功的上传方式
    const response = await uploadPic({}, file)
    
    if ((response as any).code === '00000' && (response as any).data) {
      const filePath = (response as any).data.previewUrl
      
      // 更新用户头像信息
      await updateUser({
        userId: props.userInfo?.userId,
        filePath: filePath
      })
      
      message.success('头像上传成功！')
      
      // 触发父组件更新
      emit('profile-updated', { 
        ...props.userInfo, 
        filePath: filePath
      })
      
      // 同时更新authStore中的用户信息
      authStore.updateUserInfo({
        filePath: filePath
      })
      
      console.log('头像上传成功，MinIO地址:', filePath)
    } else {
      throw new Error((response as any).message || '头像上传失败')
    }
  } catch (error: any) {
    console.error('头像上传失败:', error)
    
    let errMsg = '头像上传失败'
    if (error.response?.status === 500) {
      errMsg = '服务器内部错误，请稍后重试'
    } else if (error.response?.status === 413) {
      errMsg = '文件太大，请选择小于2MB的图片'
    } else if (error.message) {
      errMsg = error.message
    }
    
    message.error(errMsg)
  } finally {
    // 清空文件输入框
    if (target) target.value = ''
  }
}

const handleProfileUpdated = (updatedUserInfo: UserInfo) => {
  emit('profile-updated', updatedUserInfo)
}
</script>

<style scoped>
.user-profile-header {
  background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
  color: white;
  padding: 20px;
  border-radius: 12px;
  margin-bottom: 20px;
}

.profile-main {
  display: flex;
  align-items: flex-start;
  gap: 20px;
}

.avatar-section {
  position: relative;
  flex-shrink: 0;
}

.avatar-wrapper {
  position: relative;
  cursor: pointer;
}

.user-avatar {
  border: 3px solid rgba(255, 255, 255, 0.3);
  transition: all 0.3s ease;
}

.avatar-upload-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
  cursor: pointer;
}

.avatar-wrapper:hover .avatar-upload-overlay {
  opacity: 1;
}

.upload-icon {
  color: white;
  font-size: 20px;
}

.user-info {
  flex: 1;
  min-width: 0;
}

.username-section {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
}

.username {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: white;
}

.edit-icon {
  color: #ff4d4f;
  font-size: 18px;
  cursor: pointer;
  transition: color 0.3s ease;
}

.edit-icon:hover {
  color: #ff7875;
}

.stats-section {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.stat-label {
  font-size: 14px;
  opacity: 0.8;
}

.stat-value {
  font-size: 16px;
  font-weight: 600;
}

.live-indicator {
  display: flex;
  align-items: center;
  gap: 5px;
  background: rgba(255, 77, 79, 0.2);
  padding: 4px 8px;
  border-radius: 12px;
}

.live-dot {
  width: 8px;
  height: 8px;
  background: #ff4d4f;
  border-radius: 50%;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}

.live-text {
  font-size: 12px;
  color: #ff4d4f;
  font-weight: 500;
}

.account-info {
  display: flex;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
}

.email-info {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
  opacity: 0.9;
}

.gender-info {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
}

.gender-icon {
  font-size: 16px;
}

.gender-icon.female {
  color: #eb2f96;
}

.gender-icon.male {
  color: #1890ff;
}

.divider {
  height: 1px;
  background: rgba(255, 255, 255, 0.2);
  margin: 20px 0 0 0;
}

.icon {
  font-size: 14px;
  opacity: 0.8;
}

@media (max-width: 768px) {
  .profile-main {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }
  
  .stats-section {
    justify-content: center;
  }
  
  .account-info {
    justify-content: center;
  }
  
  .username-section {
    justify-content: center;
  }
}
</style>
